<template>
  <div class="page-same-city">
    <div class="distribution-bind-set gray-box top-redius border-bottom-gray">
      <div
        class=""
        style="font-size: 25px; font-weight: 500; height: 50px"
      >
        {{ $t('shop.sameCityDelFun') }}
      </div>
      <div
        class=""
        style="font-size: 15px; font-weight: 500; height: 40px"
      >
        <span>{{ $t('shop.enableStatus') }}：</span>
        <el-switch
          v-model="dataForm.status"
          @change="onSwitchSameCity()"
        />
      </div>
      <div class="">
        <span>{{ $t('shop.deliSerProByYou') }}</span>
      </div>
    </div>
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="120px"
      @submit.prevent
    >
      <el-form-item :label="$t('shop.charges') + '：'">
        <div>
          <div>
            <el-radio
              v-model="dataForm.chargeType"
              :label="1"
            >
              {{
                $t('shop.chaDelFeeByReg')
              }}
            </el-radio>
            <el-radio
              v-model="dataForm.chargeType"
              :label="2"
            >
              {{
                $t('shop.delFeeChaDis')
              }}
            </el-radio>
          </div>
          <span
            v-if="dataForm.chargeType === 1"
            style="color: gray"
          >{{
            $t('shop.chaFixDelFeeByRe')
          }}</span>
          <span
            v-if="dataForm.chargeType === 2"
            style="color: gray"
          >{{
            $t('shop.byWalkDis')
          }}</span>
        </div>
      </el-form-item>
      <el-form-item
        :label="$t('shop.startingFeeY') + '：'"
        prop="startingFee"
      >
        <el-col :span="6">
          <el-input-number
            v-model="dataForm.startingFee"
            :placeholder="$t('shop.startingFee')"
            :precision="2"
            :step="0.01"
            :min="0.0"
          />
        </el-col>
      </el-form-item>
      <el-form-item
        v-if="dataForm.chargeType === 1"
        :label="$t('shop.deliveryFeeY') + '：'"
        prop="deliveryFee"
      >
        <el-col :span="6">
          <el-input-number
            v-model="dataForm.deliveryFee"
            :placeholder="$t('shop.deliveryFee')"
            :precision="2"
            :step="0.01"
            :min="0.0"
          />
        </el-col>
      </el-form-item>
      <el-form-item
        v-if="dataForm.chargeType === 2"
        :label="$t('shop.costAllocation') + '：'"
        style="color: gray"
        prop="headDistance"
      >
        <el-input-number
          v-model="dataForm.headDistance"
          :precision="1"
          :min="0.1"
          :step="0.1"
        />
        <span>{{ $t('shop.withinKm') }}</span>
        <el-input-number
          v-model="dataForm.deliveryFee"
          :precision="2"
          :min="0.0"
          :step="0.01"
        />
        <span>{{ $t('shop.yuanToChaDelFee') }}</span>
        <el-input-number
          v-model="dataForm.overDistance"
          :precision="1"
          :step="0.1"
          :min="0.1"
        />
        <span>km，{{ $t('shop.incInDelFees') }}</span>
        <el-input-number
          v-model="dataForm.overDistanceFee"
          :precision="2"
          :step="0.01"
          :min="0.01"
        />
        <span>{{ $t('admin.dollar') }}。</span>
      </el-form-item>
      <el-form-item
        :label="$t('shop.renewalCharge') + '：'"
        prop="prodName"
        style="color: gray"
      >
        <span>{{ $t('shop.commodityWeight') }}</span>
        <el-input-number
          v-model="dataForm.freeWeight"
          :precision="3"
          :step="0.001"
          :min="0.001"
          :placeholder="$t('shop.pleaseEnterTheWeight')"
        />
        <span>{{ $t('shop.noExtraCharge') }}</span>
        <el-input-number
          v-model="dataForm.overWeight"
          :precision="3"
          :step="0.001"
          :min="0.001"
          :placeholder="$t('shop.pleaseEnterTheWeight')"
        />
        <span>kg，{{ $t('shop.renewalFeeIncrease') }}</span>
        <el-input-number
          v-model="dataForm.overWeightFee"
          :precision="2"
          :step="0.01"
          :min="0.01"
        />
        <span>{{ $t('admin.dollar') }}。</span>
      </el-form-item>
      <el-row>
        <el-col :span="8">
          <el-form-item
            :label="$t('address.province') + '：'"
            prop="province"
          >
            <el-select
              v-model="dataForm.provinceId"
              :placeholder="$t('tip.select')"
              @change="onSelectProvince"
            >
              <el-option
                v-for="province in provinceList"
                :key="province.areaId"
                :label="province.areaName"
                :value="province.areaId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            prop="city"
            :label="$t('address.city')"
          >
            <el-select
              ref="selectCityRef"
              v-model="dataForm.cityId"
              :placeholder="$t('tip.select')"
              @change="onSelectCity"
            >
              <el-option
                v-for="city in cityList"
                :key="city.areaId"
                :label="city.areaName"
                :value="city.areaId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            prop="area"
            :label="$t('temp.area')"
          >
            <el-select
              v-model="dataForm.areaId"
              :placeholder="$t('tip.select')"
              @change="selectArea"
            >
              <el-option
                v-for="area in areaList"
                :key="area.areaId"
                :label="area.areaName"
                :value="area.areaId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item
        :label="$t('shop.shopAddress') + '：'"
        prop="shopAddress"
      >
        <el-input
          v-model="dataForm.shopAddress"
          class="shopAddress"
          maxlength="99"
          @change="onMapLocation"
        />
      </el-form-item>
      <el-form-item
        prop="brief"
        :label="$t('product.deliveryArea') + '：'"
      >
        <div class="map">
          <tmap
            ref="tmapRef"
            :lat-lng="latLng"
            :is-update-coordinates="false"
            @set-polygon-path="onSetPolygonPath"
            @change-lat-lng="onChangeLatLng"
          />
        </div>
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn text-btn"
          @click="onResetMapPoint()"
        >
          {{ $t('shop.resetMap') }}
        </div>
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn primary-btn"
          @click="onSubmit()"
        >
          {{ $t('order.save') }}
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import Big from 'big.js'
import { ElMessage } from 'element-plus'

const dataRule = {
  startingFee: [{ required: true, message: $t('shop.stargFeeCannoEmp'), trigger: 'blur' }],
  deliveryFee: [{ required: true, message: $t('shop.delFeeCannoEmp'), trigger: 'blur' }],
  shopAddress: [{ required: true, trigger: 'blur', message: $t('shop.shopAddressNotNullTips') }]
}
onMounted(() => {
  if (TMap) {
    onGetSameCityDetail()
  } else {
    onGetTMap()
  }
})

let time = null
let TMap = window.TMap
const onGetTMap = () => {
  time = setTimeout(() => {
    TMap = window.TMap
    if (TMap) {
      time = null
      onGetSameCityDetail()
    } else {
      onGetTMap()
    }
  }, 500)
}

const dataForm = ref({
  chargeType: 1,
  samecityId: 0,
  shopId: 0,
  status: false,
  polygonPath: [],
  startingFee: 0.0,
  deliveryFee: 0.0,
  headDistance: 0.0,
  overDistance: 0.0,
  overDistanceFee: 0.0,
  freeWeight: 0.0,
  overWeight: 0.0,
  overWeightFee: 0.0,
  shopLat: 39.908821,
  shopLng: 116.397469,
  province: '',
  city: '',
  area: '',
  shopAddress: '',
  areaId: null,
  cityId: null,
  provinceId: null,
  tel: ''
})
const cityList = ref([])
const areaList = ref([])
const provinceList = ref([])
const polygonPath = ref([])
const tmapRef = ref(null)
// 设置默认值则初始定位到默认值，否则根据ip定位
const latLng = ref({
  lat: 39.908821,
  lng: 116.397469
})
/**
 * 获取店铺同城配送的配置
 */
const onGetSameCityDetail = () => {
  polygonPath.value = []
  cityList.value = []
  areaList.value = []
  dataForm.value.provinceId = null
  dataForm.value.cityId = null
  dataForm.value.areaId = null
  http({
    url: http.adornUrl('/delivery/sameCity/getSameCityInfo'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    if (data) {
      dataForm.value = data
      polygonPath.value = data.polygonPath || []
      dataForm.value.status = dataForm.value.status === 1
      latLng.value = {
        lat: dataForm.value.shopLat,
        lng: dataForm.value.shopLng
      }
      onListAreaByParentId(data.provinceId).then(({ data }) => {
        cityList.value = data
      })
      onListAreaByParentId(data.cityId).then(({ data }) => {
        areaList.value = data
      })
    }
    if (!dataForm.value.samecityId || !polygonPath.value || polygonPath.value.length <= 0) {
      if (
        (!dataForm.value.shopLng && dataForm.value.shopLng !== 0) ||
        (!dataForm.value.shopLat && dataForm.value.shopLat !== 0)
      ) {
        return
      }
      const points = onGetPoint({ shopLng: dataForm.value.shopLng, shopLat: dataForm.value.shopLat })
      polygonPath.value.push(...points)
      nextTick(() => {
        isConfigureAreaDefault.value = true
        tmapRef.value?.onInitGemotryEditor(polygonPath.value)
        tmapRef.value?.onSetZoom(13)
      })
    } else {
      const polygonArray = JSON.parse(JSON.stringify(polygonPath.value))
      polygonPath.value.length = 0
      polygonArray.forEach((item) => {
        const point = new TMap.LatLng(item.lat, item.lng)
        polygonPath.value.push(point)
      })
      nextTick(() => {
        isConfigureAreaDefault.value = false
        tmapRef.value?.onInitGemotryEditor(polygonPath.value)
        tmapRef.value?.onSetZoom(13)
      })
    }
  })
  onListAreaByParentId().then(({ data }) => {
    provinceList.value = data
  })
}

const onListAreaByParentId = pid => {
  const paramData = {}
  if (!pid) {
    paramData.level = 1
  } else {
    paramData.pid = pid
  }
  return http({
    url: http.adornUrl('/admin/area/listByPid'),
    method: 'get',
    params: http.adornParams(paramData)
  })
}
const onGetCurrentChild = (curList, curId) => {
  for (const item of curList) {
    if (item.areaId === curId) {
      return {
        curNode: item,
        areas: item.areas
      }
    }
  }
}
// 选择省
const onSelectProvince = val => {
  dataForm.value.cityId = null
  dataForm.value.city = ''
  dataForm.value.areaId = null
  dataForm.value.area = ''
  areaList.value = []
  // 获取城市的select
  const { curNode, areas } = onGetCurrentChild(provinceList.value, val)
  dataForm.value.province = curNode.areaName
  if (areas) {
    cityList.value = areas
  } else {
    onListAreaByParentId(val).then(({ data }) => {
      curNode.areas = data
      cityList.value = data
    })
  }
}
// 选择市
const selectCityRef = ref(null)
const onSelectCity = val => {
  dataForm.value.areaId = null
  dataForm.value.area = ''
  // 获取区的select
  const { curNode, areas } = onGetCurrentChild(cityList.value, val)
  dataForm.value.city = curNode.areaName
  if (areas) {
    areaList.value = areas
  } else {
    onListAreaByParentId(val).then(({ data }) => {
      curNode.areas = data
      areaList.value = data
    })
  }
}
const selectArea = val => {
  const { curNode } = onGetCurrentChild(areaList.value, val)
  dataForm.value.area = curNode.areaName
  onMapLocation()
}
// 错误提示
const errorMsg = message => {
  ElMessage({
    message,
    type: 'error',
    duration: 1500
  })
}

/**
 * 通过省市区id,得到省市区名称
 */
const onGetAreaName = () => {
  for (let i = 0; i < provinceList.value.length; i++) {
    if (provinceList.value[i].areaId === dataForm.value.provinceId) {
      // 将省名字保存起来
      dataForm.value.province = provinceList.value[i].areaName
    }
  }
  for (let i = 0; i < cityList.value.length; i++) {
    if (cityList.value[i].areaId === dataForm.value.cityId) {
      // 将市名字保存起来
      dataForm.value.city = cityList.value[i].areaName
    }
  }
  for (let i = 0; i < areaList.value.length; i++) {
    if (areaList.value[i].areaId === dataForm.value.areaId) {
      // 将市名字保存起来
      dataForm.value.area = areaList.value[i].areaName
    }
  }
}

// 腾讯地图
const onMapLocation = () => {
  let address = ''
  const { provinceId, province, cityId, city, areaId, area, shopAddress } = dataForm.value
  // 选择省市区时，定位地图
  if (provinceId) {
    address = province
    tmapRef.value.onSetZoom(6)
    if (cityId) {
      address = address + city
      tmapRef.value.onSetZoom(10)
      if (areaId) {
        address = address + area
        tmapRef.value.onSetZoom(18)
        if (shopAddress) {
          // 详细地址
          address = address + shopAddress
          tmapRef.value.onSetZoom(18)
        }
      }
    }
  }
  if (address) {
    tmapRef.value.onGetLocation(address).then(res => {
      onChangeLatLng(res)
      // 更改坐标点后，重新设置地图选区
      const points = onGetPoint({ shopLng: dataForm.value.shopLng, shopLat: dataForm.value.shopLat })
      polygonPath.value.length = 0
      polygonPath.value.push(...points)
      nextTick(() => {
        tmapRef.value?.onResetGemotryEditor(polygonPath.value)
      })
    })
  }
}

/**
 * 获取区域点坐标
 * @param latLng
 * @returns {[TMap.LatLng,TMap.LatLng,TMap.LatLng,TMap.LatLng]}
 */
const onGetPoint = (latLng) => {
  const lng = new Big(Number.parseFloat(latLng.shopLng))
  const lat = new Big(Number.parseFloat(latLng.shopLat))
  const point1 = new TMap.LatLng(
    Number.parseFloat(lat),
    Number.parseFloat(lng)
  )
  const point2 = new TMap.LatLng(
    Number.parseFloat(lat.plus(0.01)),
    Number.parseFloat(lng.plus(0.01))
  )
  const point3 = new TMap.LatLng(
    Number.parseFloat(lat.plus(0.02)),
    Number.parseFloat(lng.plus(0.02))
  )
  const point4 = new TMap.LatLng(
    Number.parseFloat(lat.plus(0.01001)),
    Number.parseFloat(lng.plus(0.01001))
  )
  isConfigureAreaDefault.value = true
  return [point1, point2, point3, point4]
}

// 修改经纬度
const onChangeLatLng = (latLngInfo) => {
  const { lng, lat } = latLngInfo
  latLng.value = latLngInfo
  dataForm.value.shopLng = lng
  dataForm.value.shopLat = lat
  isConfigureAreaDefault.value = true
}

const onSwitchSameCity = () => {
  if (
    dataForm.value.shopLng === '' ||
    dataForm.value.shopLng === null ||
    dataForm.value.shopLat === null ||
    dataForm.value.shopLat === ''
  ) {
    dataForm.value.status = !dataForm.value.status
  }
}
// 表单提交
const dataFormRef = ref(null)
const isConfigureAreaDefault = ref(true)
const onResetMapPoint = () => {
  dataForm.value.status = dataForm.value.status ? 1 : 0
  dataForm.value.polygonPath = null
  polygonPath.value = null
  onGetAreaName()
  if (!dataForm.value.province) {
    errorMsg($t('shop.provinceNotNullTips'))
    return
  }
  if (!dataForm.value.city) {
    errorMsg($t('shop.cityNotNullTips'))
    return
  }
  if (!dataForm.value.area) {
    errorMsg($t('shop.areaNotNullTips'))
    return
  }
  dataFormRef.value.validate(valid => {
    if (valid) {
      http({
        url: http.adornUrl('/delivery/sameCity'),
        method: dataForm.value.samecityId ? 'put' : 'post',
        data: http.adornData(dataForm.value)
      }).then(() => {
        dataForm.value.status = dataForm.value.status === 1
        polygonPath.value = []
        isConfigureAreaDefault.value = true
        if (
          (!dataForm.value.shopLng && dataForm.value.shopLng !== 0) ||
          (!dataForm.value.shopLat && dataForm.value.shopLat !== 0)
        ) {
          return
        }
        const points = onGetPoint({ shopLng: dataForm.value.shopLng, shopLat: dataForm.value.shopLat })
        polygonPath.value.push(...points)
        tmapRef.value?.onResetGemotryEditor(polygonPath.value)
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500
        })
      })
    }
  })
}

// 表单提交
const isDataTrue = ref(false)

const onSubmit = () => {
  onCheckData()
  if (!isDataTrue.value) {
    return
  }

  dataForm.value.polygonPath = polygonPath.value
  dataForm.value.status = dataForm.value.status ? 1 : 0

  if (isConfigureAreaDefault.value && dataForm.value.status === false) dataForm.value.polygonPath = []

  dataFormRef.value.validate(valid => {
    if (valid) {
      http({
        url: http.adornUrl('/delivery/sameCity'),
        method: dataForm.value.samecityId ? 'put' : 'post',
        data: http.adornData(dataForm.value)
      }).then(() => {
        dataForm.value.status = dataForm.value.status === 1
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500
        })
      })
    }
  })
}
const onCheckData = () => {
  if (dataForm.value.overWeightFee == null) {
    onErrorMsg($t('shop.costCannotBeEmpty'))
    isDataTrue.value = false
    return
  }
  if (dataForm.value.chargeType === 2 && dataForm.value.overDistanceFee == null) {
    onErrorMsg($t('shop.excDisFeeCanBeEm'))
    isDataTrue.value = false
    return
  }
  if (
    dataForm.value.chargeType === 2 &&
    (dataForm.value.headDistance == null || dataForm.value.overDistance == null)
  ) {
    onErrorMsg($t('shop.distanceCannotBeEmpty'))
    isDataTrue.value = false
    return
  }
  if (!dataForm.value.freeWeight == null || !dataForm.value.overWeight == null) {
    onErrorMsg($t('shop.weightCannotBeEmpty'))
    isDataTrue.value = false
    return
  }
  if (polygonPath.value != null && polygonPath.value.length > 12) {
    onErrorMsg($t('shop.polygonPathOverNum'))
    isDataTrue.value = false
    return
  }
  if (!dataForm.value.province) {
    onErrorMsg($t('shop.provinceNotNullTips'))
    isDataTrue.value = false
    return
  }
  if (!dataForm.value.city) {
    onErrorMsg($t('shop.cityNotNullTips'))
    isDataTrue.value = false
    return
  }
  if (!dataForm.value.area) {
    onErrorMsg($t('shop.areaNotNullTips'))
    isDataTrue.value = false
    return
  }
  if (dataForm.value.status && isConfigureAreaDefault.value) {
    onErrorMsg($t('shop.setArea'))
    isDataTrue.value = false
    return
  }
  isDataTrue.value = true
}
const onErrorMsg = message => {
  ElMessage({
    message,
    type: 'error',
    duration: 1500
  })
}
const onSetPolygonPath = (data) => {
  isConfigureAreaDefault.value = false
  polygonPath.value.length = 0
  polygonPath.value.push(...data.paths)
}

onUnmounted(() => {
  if (time) {
    clearTimeout(time)
  }
})
</script>
<style lang="scss" scoped>
.page-same-city {
  .border-bottom-gray {
    border-bottom: 1px solid #dddce2;
  }
  .distribution-bind-set {
    :deep(.el-form-item--mini) {
      display: inline-block;
    }
    :deep(.el-form-item__content) {
      margin-left: 0 !important;
    }
  }
  .gray-box {
    background: #f2f2f6;
    padding: 20px 35px;
    height: 100%;
  }
  .map {
    width: 50%;
    height: 500px;
  }
  :deep(.el-input-number__increase) {
    right: 1px !important;
    border-left: 1px solid #dcdfe6 !important;
  }
}
</style>
